package stewarduploadhandler

import (
	"errors"
	"fmt"
	"github.com/aliyun/aliyun-oss-go-sdk/oss"
	"github.com/gin-gonic/gin"
	"log"
	"mime/multipart"
	"os"
	"path"
	"path/filepath"
	"strings"
	"time"
	"yundian/internel/app/dao"
	"yundian/internel/app/helper"
	"yundian/internel/app/models/users"
	"yundian/internel/pkg/dingo"
	"yundian/internel/pkg/dingo/global"
	. "yundian/internel/pkg/dingo/result"
	"yundian/internel/pkg/utils"
)

// CommonUploadGoodsImg 上传图片
func CommonUploadGoodsImg(ctx *gin.Context, fileDir, host, hostPath string) {
	var md5Name string
	var file *multipart.FileHeader
	var err error

	if file, err = ctx.FormFile("file"); err != nil || file == nil {
		Response(ctx)("上传失败!", CodeError, nil)(Error)
		return
	}

	if md5Name, err = utils.GetHeadFileMD5(file); err != nil {
		Response(ctx)("上传失败，文件读取错误", CodeError, nil)(Error)
		return
	}

	imgType := []string{"image/bmp", "image/png", "image/gif", "image/jpg", "image/jpeg", "image/pjpeg", "image/x-png", "image/svg"}
	if !utils.Contains(imgType, file.Header.Get("Content-Type")) {
		Response(ctx)("上传失败!文件类型错误", CodeError, nil)(Error)
	}

	if file.Size > 10485760 {
		Response(ctx)("上传失败!只允许小于10M的文件", CodeError, nil)(Error)
		return
	}

	newFileName := md5Name + filepath.Ext(file.Filename)
	filePathInfo := filepath.Join(fileDir, newFileName)
	_ = os.MkdirAll(fileDir, os.ModePerm)
	err = ctx.SaveUploadedFile(file, filePathInfo)

	Response(ctx)("", CodeSuccess, map[string]interface{}{
		"host":     host,
		"hostPath": hostPath,
		"fileName": newFileName,
	})(OK)
}

func AliOssUploadImage(c *gin.Context) {
	file, err := c.FormFile("file")

	if err != nil {
		Response(c)("上传失败!请上传文件", CodeError, nil)(Error)
	}
	imgType := []string{"image/bmp", "image/png", "image/gif", "image/jpg", "image/jpeg", "image/pjpeg", "image/x-png"}
	fileExt := strings.ToLower(path.Ext(file.Filename))
	// 判断 文件类型
	if !utils.Contains(imgType, file.Header.Get("Content-Type")) {
		Response(c)("上传失败!文件类型错误", CodeError, nil)(Error)
	}
	// 判断 文件后缀
	if fileExt != ".png" && fileExt != ".jpg" && fileExt != ".gif" && fileExt != ".jpeg" {
		Response(c)("上传失败!只允许png,jpg,gif,jpeg文件", CodeError, nil)(Error)
	}
	// 判断 文件大小 1024*1024*10
	if file.Size > 10485760 {
		Response(c)("上传失败!只允许小于10M的文件", CodeError, nil)(Error)
	}
	fileName := utils.Str2Md5(fmt.Sprintf("%s%s", file.Filename, time.Now().String()))
	//访问域名
	endpoint := global.Cfg.Ali.AliossEndpoint
	accessKeyId := global.Cfg.Ali.AccessKey
	accessKeySecret := global.Cfg.Ali.AccessKeySecret
	bucketName := global.Cfg.Ali.AliossBucketName
	//上传文件到OSS时需要指定包含文件后缀在内的完整路径。
	dir := global.Cfg.Ali.AliossUploadImgDir + fileName + fileExt
	// 创建OSSClient实例。
	client, err := oss.New(endpoint, accessKeyId, accessKeySecret)
	if err != nil {
		log.Println(err)
	}
	// 获取存储空间。
	bucket, err := client.Bucket(bucketName)
	if err != nil {
		log.Println(err)
	}

	fileIo, err := file.Open()
	// 上传文件流。
	err = bucket.PutObject(dir, fileIo)
	if err != nil {
		log.Println(err)
	}
	//拼接域名返回给前端
	//filePath := global.Cfg.Ali.AliossPath + "/" + dir
	//Response(c)("", CodeSuccess, filePath)(OK)

	Response(c)("", CodeSuccess, map[string]interface{}{
		"host":     global.Cfg.Ali.AliossPath,
		"hostPath": "/" + global.Cfg.Ali.AliossUploadImgDir,
		"fileName": fileName + fileExt,
	})(OK)
}

// HandleStewardUploadGoodsImg 上传商品图片
func HandleStewardUploadGoodsImg(ctx *gin.Context) {
	//CommonUploadGoodsImg(ctx, "./static/goods", helper.UploadHost, "/static/goods/")
	AliOssUploadImage(ctx)
}

func CommonAliOssUploadImage(file *multipart.FileHeader) (map[string]string, error) {

	imgType := []string{"image/bmp", "image/png", "image/gif", "image/jpg", "image/jpeg", "image/pjpeg", "image/x-png"}
	fileExt := strings.ToLower(path.Ext(file.Filename))

	if !utils.Contains(imgType, file.Header.Get("Content-Type")) {
		return nil, errors.New("上传失败!文件类型错误")
	}

	if fileExt != ".png" && fileExt != ".jpg" && fileExt != ".gif" && fileExt != ".jpeg" {
		return nil, errors.New("上传失败!只允许png,jpg,gif,jpeg文件")
	}

	if file.Size > 10485760 {
		return nil, errors.New("上传失败!只允许小于10M的文件")
	}

	fileName := utils.Str2Md5(fmt.Sprintf("%s%s", file.Filename, time.Now().String()))
	endpoint := global.Cfg.Ali.AliossEndpoint
	accessKeyId := global.Cfg.Ali.AccessKey
	accessKeySecret := global.Cfg.Ali.AccessKeySecret
	bucketName := global.Cfg.Ali.AliossBucketName
	dir := global.Cfg.Ali.AliossUploadImgDir + fileName + fileExt
	client, err := oss.New(endpoint, accessKeyId, accessKeySecret)
	if err != nil {
		log.Println(err)
		return nil, err
	}

	bucket, err := client.Bucket(bucketName)
	if err != nil {
		log.Println(err)
		return nil, err
	}
	fileIo, err := file.Open()
	err = bucket.PutObject(dir, fileIo)
	if err != nil {
		log.Println(err)
		return nil, err
	}

	return map[string]string{"host": global.Cfg.Ali.AliossPath, "hostPath": "/" + global.Cfg.Ali.AliossUploadImgDir, "fileName": fileName + fileExt}, nil
}

// 上传二维码
func HandleQRCodePathUploadImg(c *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(c)
	dingo.ErrorIf(err).Unwrap()

	file, err := c.FormFile("file")
	if err != nil {
		Response(c)("上传失败!请上传文件", CodeError, nil)(Error)
		return
	}

	imgInfo, _ := CommonAliOssUploadImage(file)

	log.Println("上传二维码图片，", imgInfo, "当前用户", userId)
	userModel := &users.UserModel{}
	userModel.WxIncomeQrcode = imgInfo["host"] + imgInfo["hostPath"] + imgInfo["fileName"]
	dao.NewUserDao().UpdateUserQRCode(userId, userModel).Unwrap()

	//响应给前端
	Response(c)("", CodeSuccess, imgInfo)(OK)

}
